package com.gwt.tirso.gymkhana.client;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwt.tirso.gymkhana.shared.DelistedException;
import com.gwt.tirso.gymkhana.shared.FieldVerifier;

public class ContestStep1 implements EntryPoint{
	
	private Label gymkLabel = new Label("Nombre de la Gymkhana");
	private Label passLabel = new Label("Contraseña");
	private TextBox gymkNameBox = new TextBox();
	private PasswordTextBox passBox = new PasswordTextBox();
	private Button acceptBt =  new Button("Aceptar");
	private Button cancelBt = new Button("Cancel");
	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel buttonsPanel = new HorizontalPanel();
	private Label errorLabel = new Label("");
	
	private ILoginServiceAsync login;
	private IContestServiceAsync contestCon;
	
	private Gymkhana g;

	@Override
	public void onModuleLoad() {
		
		loadContestStep1();
		
	}
	
	private void loadContestStep1(){
		//adding elements to mainPanel
		mainPanel.add(gymkLabel);
		mainPanel.add(gymkNameBox);
		mainPanel.add(passLabel);
		mainPanel.add(passBox);
		
		//adding buttons to buttonsPanel
		buttonsPanel.add(acceptBt);
		buttonsPanel.add(cancelBt);
		
		mainPanel.add(buttonsPanel);
		mainPanel.add(errorLabel);
		
		login = ConnectionRpc.initRpcLogin();
		contestCon = ConnectionRpc.initRpcContest();
		
		//handling buttons operations
		acceptBt.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				eventClick();
			}
		});
		
		cancelBt.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				cancelStep();				
			}
		});
		
		mainPanel.addStyleName("contestNext");
		RootPanel.get("contest").add(mainPanel);
	}
	
	protected void eventClick() {
		
		login.loginFromSessionServer(new AsyncCallback<Person>() {
			
			@Override
			public void onSuccess(Person result) {
				
				//if the session is initialized 
				if(result != null){
					step2();
				}else{
					Window.alert("Para acceder a la aplicación debe iniciar sesión");
				}
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				String details = caught.getMessage();
		        if (caught instanceof DelistedException) {
			          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
			        }

			        errorLabel.setText("Error: " + details);
			        errorLabel.setVisible(true);
				
			}
		});
		
	}
	
	protected void step2() {
		g = receiveInfo();
		if(g == null){
			errorLabel.setVisible(true);
			return;
		}
		
		contestCon.extractGymkhana(g.getName(), g.getPass(), new AsyncCallback<Gymkhana>() {

			@Override
			public void onFailure(Throwable caught) {
				String details = caught.getMessage();
		        if (caught instanceof DelistedException) {
		          details = "Company '" + ((DelistedException)caught).getSymbol() + "' was delisted";
		        }

		        errorLabel.setText("Error: " + details);
		        errorLabel.setVisible(true);				
			}

			@Override
			public void onSuccess(Gymkhana result) {
				g = result;
				if(g == null){
					errorLabel.setText("No existe ninguna Gymkhana con ese nombre y contraseña");
					errorLabel.setVisible(true);
					
				}else{
					ContestStep2 c2 = new ContestStep2();
					c2.setGymkhana(g);
					c2.onModuleLoad();
					RootPanel.get("contest").remove(mainPanel);			
				}
			}
		});
	}

	private Gymkhana receiveInfo() {
		
		Gymkhana gymk = new Gymkhana();
		
		String gymkName = gymkNameBox.getText();
		String gymkPass = passBox.getText();
		
		if(!FieldVerifier.isValidName(gymkName)||!FieldVerifier.isValidName(gymkPass)){
			errorLabel.setText("El usuario o la contraseña no están bien escritos");
			return null;
		}
		
		gymk.setName(gymkName);
		gymk.setPass(gymkPass);
		
		return gymk;
		
	}

	public void cancelStep(){
		GymkhanaWeb gw = new GymkhanaWeb();
		gw.onModuleLoad();
		RootPanel.get("contest").remove(mainPanel);
	}
}
